<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/5/9
 * Time: 10:58
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\common\business;

use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\MallGoodsSku;
use app\common\model\MallOrder;
use app\common\model\MallOrderGoods;
use think\Exception;

class BusOrder extends Base
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new MallOrder();
    }

    /**
     * 处理取消订单
     * @param array $ids
     * @return bool
     * @throws Exception
     */
    public function CancelOrder(array $ids = []): bool
    {
        $orderGods_obj = new MallOrderGoods();
        try {
            $orderGoods = $orderGods_obj->getOrderGoodsByOrderIdsAll($ids);
        } catch (\Exception $e) {
            throw new Exception("处理失败");
        }
        if (!empty($orderGoods)) {
            $update_data = [];
            foreach ($orderGoods as $v) {
                $update_data[] = [
                    "id" => $v['goodsSku']['id'],
                    "stock" => $v['goodsSku']['stock'] + $v['total']
                ];
            }
            $this->model->startTrans();
            try {
                (new MallGoodsSku())->saveAll($update_data);
                $this->model->destroy($ids);
                //$order_ids = array_column($orderGoods, 'id');
                //$orderGods_obj->whereIn('id', $order_ids)->delete();
                $this->model->commit();
            } catch (\Exception $e) {

                $this->model->rollback();
                throw new Exception("订单处理失败");
            }
            return true;

        } else {
            return false;
        }
    }

    /**
     * @param string $order_id
     * @param string $field
     * @return bool
     * @throws Exception
     */
    public function getOrderByOrderIdInfo(string $order_id = "", string $field = "*"): bool
    {
        try {
            $result = $this->model->getOrderByOrderId($order_id, $field);
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        if (empty($result)) {
            throw new Exception("订单不存在");
        }
        $res = $this->CancelOrder([$result['id']]);
        if ($res) {
            return true;
        } else {
            return false;
        }
    }
}